package com.team3.ecommerce.service;

        import com.team3.ecommerce.domain.UserAuth;
        import com.team3.ecommerce.domain.UserAuthExample;
        import com.team3.ecommerce.domain.UserInfo;
        import com.team3.ecommerce.mapper.UserAuthMapper;
        import com.team3.ecommerce.mapper.UserInfoMapper;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.beans.propertyeditors.StringTrimmerEditor;
        import org.springframework.security.core.userdetails.UserDetails;
        import org.springframework.security.core.userdetails.UserDetailsService;
        import org.springframework.security.core.userdetails.UsernameNotFoundException;
        import org.springframework.stereotype.Service;
        import org.springframework.web.bind.WebDataBinder;
        import org.springframework.web.bind.annotation.InitBinder;

        import java.security.Principal;
        import java.util.List;
        import java.util.UUID;


@Service
public class UserAuthServiceImp implements UserAuthService,UserDetailsService{

    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public boolean userReg(UserAuth userToBeReg, UserInfo userInfo) {
        String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        userToBeReg.setUserUid(uid);
        userInfo.setUserUid(uid);
        userAuthMapper.insert(userToBeReg);
        if(userInfo.getBirthdate()!=null && userInfo.getBirthdate().toString().isEmpty())
        {
            userInfo.setBirthdate(null);
        }
        userInfoMapper.insert(userInfo);
        return true;
    }

    @Override
    public UserAuth findUserByPrincipal(Principal principal) {
        UserAuthExample example = new UserAuthExample();
        example.or().andPhonenumberEqualTo(principal.getName());
        return userAuthMapper.selectByExample(example).get(0);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserAuthExample example = new UserAuthExample();
        example.or().andPhonenumberEqualTo(s);
        List<UserAuth> userAuths = userAuthMapper.selectByExample(example);
        if (userAuths.size()!=0)
            return userAuths.get(0);
        else
            throw new UsernameNotFoundException("admin: " + s + " do not exist!");
    }

    @Override
    public boolean checkDupPhone(String phonenumber) {
        UserAuthExample example = new UserAuthExample();
        example.or().andPhonenumberEqualTo(phonenumber);
        if(userAuthMapper.selectByExample(example).size()!=0)
            return true;
        else
            return false;
    }
}
